package com.xzr.hospitalregister.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.xzr.hospitalregister.R;
import com.xzr.hospitalregister.base.BaseActivity;
import com.xzr.hospitalregister.config.HttpUrl;
import com.xzr.hospitalregister.config.UpdateManager;
import com.xzr.hospitalregister.util.GetTokenFromClientAPK;
import com.xzr.hospitalregister.util.HttpRequest;
import com.xzr.hospitalregister.view.DialogIpSet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import static android.R.attr.data;

/**
 * Created by Administrator on 2018/2/9 0009.
 */

public class PJTYPEActivity extends BaseActivity{
    private ImageView iv_ani;
    private AnimationDrawable mAnimationDrawable;
    private String deviceId;

    private String appVersion;//////////////
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        getSupportActionBar().hide();// 隐藏ActionBar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//remove notification bar  即全屏
        setContentView(R.layout.activity_pjtypt);
//        /////////
//        //////////
//        ////////
//        checkVersion();
//        PackageManager manager = this.getPackageManager();
//        PackageInfo info = null;
//        try {
//            info = manager.getPackageInfo(this.getPackageName(), 0);
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//        appVersion = info.versionName;   //版本名
//        //////////
//        ////////
//        //////////
        initWidget();
        getMac();
        initData();
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        //window初始化完毕 开始播放动画
        animationStart();
    }

    @Override
    protected void onPause() {
        animationStop();
        super.onPause();
    }

    private void animationStart() {
        if (null != mAnimationDrawable)
            mAnimationDrawable.start();//开始播放
    }

    private void animationStop() {
        if (null != mAnimationDrawable)
            mAnimationDrawable.stop();//暂停播放
    }

    @Override
    public void initWidget() {
        super.initWidget();
        iv_ani = (ImageView) findViewById(R.id.iv_ani);
        mAnimationDrawable = (AnimationDrawable) iv_ani.getDrawable();
    }

    private void getMac(){
        deviceId = GetTokenFromClientAPK.getMacAddress1();
        if (!TextUtils.isEmpty(deviceId)) {
            deviceId = deviceId.replaceAll("[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……& amp;*（）——+|{}【】‘；：”“’。，、？|-]", ""); //去标点符号
            deviceId = deviceId.toLowerCase();//大写转换成小写
            Toast.makeText(PJTYPEActivity.this, deviceId, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(PJTYPEActivity.this, "MAC地址为空", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void initData() {
        super.initData();
        getMotherYFXXTKFromRemote();
        if (ContextCompat.checkSelfPermission(PJTYPEActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(PJTYPEActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STRONGE);
        }//REQUEST_EXTERNAL_STRONGE是自定义个的一个对应码，用来验证请求是否通过


//        String TAG = "系统参数：";
//        Log.e(TAG, "手机厂商：" + MobilePhoneInfoUtil.getDeviceBrand());
//        Log.e(TAG, "手机型号：" + MobilePhoneInfoUtil.getSystemModel());
//        Log.e(TAG, "手机当前系统语言：" + MobilePhoneInfoUtil.getSystemLanguage());
//        Log.e(TAG, "Android系统版本号：" + MobilePhoneInfoUtil.getSystemVersion());
//        Log.e(TAG, "手机IMEI：" + MobilePhoneInfoUtil.getIMEI(getApplicationContext()));
//        checkAppVersion();////////////
        ///////////////
        ///////////////////
//        getMotherYFXXTKFromRemote();
    }
    ////////////////
    ////////////////
//    private void checkAppVersion() {
//        HttpRequest.getInstance().getRequestDealResultInBackgroud(HttpUrl.VERSION_CODE_INFO, new HttpRequest.DealResultInBackgroud() {
//            @Override
//            public void dealResult(Integer resultState, String result) {
//                if (resultState == 1) {
//                    try {
//                        PackageManager packageManager = getPackageManager();
//                        PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
//                        int versionCode = packageInfo.versionCode;
//                        String versionName = packageInfo.versionName;
//                        Log.e("versionInfo:", result);
//                        JsonObject jsonObject = (JsonObject) new JsonParser().parse(result);
//                        Log.e("TAG", "获取版本信息" + result);
//                        Log.e("TAG", "获取服务期的版本信息" + jsonObject.get("version").getAsInt());
//                        Log.e("TAG", "获取版本号" + jsonObject.get("versioncode").toString());/////////////////
////                        JsonObject versionInfo = jsonObject.get("versionNumber").getAsJsonObject();
////                        if (versionNumber.get("versionCode").getAsInt() > versionCode) {//服务器的版本号大于当前版本号时，正式使用
//                        if (jsonObject.get("version").getAsInt() >= versionCode) {//服务器的版本号大于等于当前版本号时，测试使用  // TODO: 2018/2/5
//                            DialogLastestVersionAppRemind dialogLastestVersionAppRemind = new DialogLastestVersionAppRemind();
//                            Bundle bundle = new Bundle();
//                            bundle.putString("versionInfo", jsonObject.toString());
//                            dialogLastestVersionAppRemind.setArguments(bundle);
//                            dialogLastestVersionAppRemind.show(getSupportFragmentManager(), "DialogLastestVersionAppRemind");
//                        }
//                    } catch (PackageManager.NameNotFoundException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        });
//    }
    ///////////////
    ///////////////
//    private String mac = "00606e5458dd";//儿童保健部—排队
//    private String mac = "00606ec858de";//儿童保健部—叫号
    private String mac = "00606e5458d4";//妇女保健部—排队deviceId
//    private String mac = "dcc0db78aa5b";
//    private String mac = "9cb2b228e24c";
    public void getMotherYFXXTKFromRemote() {
        HttpRequest.getInstance().getRequest(HttpUrl.MEN_ZHEN_GUA_HAO + "?param={\"mac\":\"" + mac + "\"}", new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.arg1 == -1) {
                    Toast.makeText(PJTYPEActivity.this, "服务器水逆了...", Toast.LENGTH_SHORT).show();
                    System.out.println("*****   " + (String) msg.obj);
                    showIpSet();
                } else if (msg.arg1 == 1) {
                    try {
                        JSONObject jsonObject = new JSONObject((String) msg.obj);
                        JSONArray jsonData = jsonObject.getJSONArray("rows");
                        Log.e("TAG","获取的状态+++++++++++++++++"+jsonObject.getString("flag"));
                        if(jsonData.length()>0) {
                            Log.e("TAG", "排队列表 jsonData.getJSONObject(0).getString(\"FLAG\")+++" + jsonData.getJSONObject(0).getString("FLAG"));
                            if (jsonData.getJSONObject(0).getString("FLAG").equals("1")) {
                                Intent intent = new Intent(PJTYPEActivity.this, HallWaitingActivity.class);
                                intent.putExtra("jsonData", (String) msg.obj);
                                startActivity(intent);
                                finish();
                            } else if (jsonData.getJSONObject(0).getString("FLAG").equals("2")) {
                                Intent intent = new Intent(PJTYPEActivity.this, CallNumberActivity.class);
                                intent.putExtra("jsonData", (String) msg.obj);
                                startActivity(intent);
                                finish();
                            }
                        }else {
                            Toast.makeText(PJTYPEActivity.this,"后台数据可能为空，请检查后台是否有数据！",Toast.LENGTH_LONG).show();
                            Log.e("TAG","后台数据可能为空，请检查后台是否有数据！");
                            if (jsonObject.getString("flag").equals("1")) {
                                Intent intent = new Intent(PJTYPEActivity.this, HallWaitingActivity.class);
                                intent.putExtra("jsonData", (String) msg.obj);
                                startActivity(intent);
                                finish();
                            } else if (jsonObject.getString("flag").equals("2")) {
                                Intent intent = new Intent(PJTYPEActivity.this, CallNumberActivity.class);
                                intent.putExtra("jsonData", (String) msg.obj);
                                startActivity(intent);
                                finish();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("排队列表   " + (String) msg.obj);
                Log.e("TAG", "排队列表 data+++" + data);
                Log.e("TAG", "排队列表 obj+++" + (String) msg.obj);

            }
        });
    }
    ///////////
    ///////////
    private static int REQUEST_EXTERNAL_STRONGE = 1;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //根据请求是否通过的返回码进行判断，然后进一步运行程序
        if (grantResults.length > 0 && requestCode == REQUEST_EXTERNAL_STRONGE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        } else
            finish();
    }
    //////////
    ///////////

    ///////
    //////////
    /////////
    /** 检查更新 */
    private void checkVersion() {
        UpdateManager manager = new UpdateManager(PJTYPEActivity.this);
        // 检查软件更新
        manager.checkUpdate();
    }
    //////////
    ////////
    ////////
    /**
     * 显示设置IP对话框
     */
    private void showIpSet() {
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.soft_update_ip_title);
        builder.setMessage(R.string.soft_update_ip_info);
        // 确定
        builder.setPositiveButton(R.string.soft_update_ip_updatebtn,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 显示设置IP对话框
                        DialogIpSet dialogIpSet = new DialogIpSet();
                        dialogIpSet.show(getSupportFragmentManager(), "DialogIpSet");
                    }
                });
        // 取消
        builder.setNegativeButton(R.string.soft_update_ip_later,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }
    /////////
}
